In this article, I will show you how to download a file using asp.net c#. Based on the file extension you can set the content type value to be get downloaded. The Response.TransmitFile retrieves file by using file server path and writes to it response.
Here the user can upload the file using file upload control and show it in a label control. When the user clicks the download button it will check whether it is text or pdf or doc or JPEG file and get downloaded as per ContentType.
Download.aspx:
<form id="form1" runat="server">
<div>
<table style="padding: 20px;">
<tr>
<td>
<asp:Label ID="lblFilename" runat="server" Text="Browse:"></asp:Label>
</td>
<td>
<asp:FileUpload ID="fileUpload1" runat="server" />
</td>
</tr>
<tr>
<td colspan="2">
</td>
</tr>
<tr>
<td>
<asp:LinkButton runat="server" OnClick="lnkUpload_Click" Font-Underline="False">Upload</asp:LinkButton>
</td>
<td>
<asp:LinkButton runat="server" OnClick="lnkDownload_Click" Font-Underline="False">Download</asp:LinkButton>
</td>
</tr>
</table>
</div>
</form>
Download.aspx.cs:
protected void lnkUpload_Click(object sender, EventArgs e)
{
filename= Path.GetFileName(fileUpload1.PostedFile.FileName);
fileUpload1.SaveAs(Server.MapPath("Uploads/" + filename));
Response.Write("Fileuploaded sucessfully.");
lblFilename.Text = "Uploads/" + fileUpload1.FileName;
}
// To download uplaoded file
protected void lnkDownload_Click(object sender, EventArgs e)
{
if (lblFilename.Text != string.Empty)
{
if (lblFilename.Text.EndsWith(".txt"))
{
Response.ContentType = "application/txt";
}
else if (lblFilename.Text.EndsWith(".pdf"))
{
Response.ContentType = "application/pdf";
}
else if (lblFilename.Text.EndsWith(".docx"))
{
Response.ContentType = "application/docx";
}
else
{
Response.ContentType = "image/jpg";
}
string filePath = lblFilename.Text;
Response.AddHeader("Content-Disposition", "attachment;filename=\"" + filePath + "\"");
Response.TransmitFile(Server.MapPath(filePath));
Response.End();
Download file to client PC:
Post your comments / questions
Recent Article
- The request was aborted: Could not create SSL/TLS secure channel -Error in Asp.net
- FieldError: Cannot resolve keyword 'id' into field in Django project
- How to hide the ID field from the Django admin?
- It is impossible to add a non nullable field without specifying a default. Django error
- ImportError: cannot import name 'url' from 'django.conf.urls' - Django Error
- How to Enable Virtualization in BIOS Security Settings in Intel Processors For Android Studio?
- Dependency 'androidx.activity:activity:1.8.0' requires libraries and applications that depend on it.
- AttributeError: 'NoneType' object has no attribute 'get_text' - Python
Related Article